package com.c2dm.servlets;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import sporteam.common.PMF;
import sporteam.web.client.AEuser;


@SuppressWarnings("serial")
public class c2dmRegistration extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String devID = (String) req.getParameter("deviceid");
		String regID = (String) req.getParameter("registrationid");
		String facebookID = (String) req.getParameter("facebookid");

		PersistenceManager pm = PMF.get().getPersistenceManager();
		String select_from_query = "SELECT FROM " + AEuser.class.getName();
		Query query = pm.newQuery("SELECT FROM " + AEuser.class.getName());
		List<AEuser> result = (List<AEuser>) query.execute();
		for (AEuser u : result) {
			if (u.GetFacebookID().equals(facebookID)) {
				u.setReg_id(regID);
				u.setDev_id(devID);
				pm.makePersistent(u);
				break;
			}
		}

		// ServerConfiguration.AUTHENTICATION_TOKEN = devID;
		// ServerConfiguration.REGISTRATION_ID = regID;
		//int responseCode = com.c2dm.data.MessageUtil.sendMessage(null, regID,
		//		"Masheuo");
		//log.warning("this is response code: " + responseCode);

		// if (result.size() != 1)
		// log.severe("result matches to more than one user");
		// result.setReg_id(regID);
		// result.setDev_id(devID);
		// pm.makePersistent(result.get(0)); // update the user in the database
		pm.close();
		resp.sendRedirect("/");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String devID = (String) req.getParameter("deviceid");
		String regID = (String) req.getParameter("registrationid");
		String facebookID = (String) req.getParameter("facebookid");

		PersistenceManager pm = PMF.get().getPersistenceManager();

		AEuser u = pm.getObjectById(AEuser.class, facebookID);
		u.setReg_id(regID);
		u.setDev_id(devID);
		pm.makePersistent(u);
	
		// if (result.size() != 1)
		// log.severe("result matches to more than one user");
		// result.setReg_id(regID);
		// result.setDev_id(devID);
		// pm.makePersistent(result.get(0)); // update the user in the database
		pm.close();
		resp.sendRedirect("/");
	}
}
